package utils;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailUtil {
	
	/**
	 * 发送邮件
	 * @param to 收件人
	 * @param content 邮件内容
	 * @param title 邮件标题
	 */
	public static boolean sendEmail(String to,String content,String title){
		boolean result = false;
		try{
			/**
			 * 1.建立连接对象，连接到服务器
			 */
			Properties props = new Properties();
			props.setProperty("mail.transport.protocol", "smtp");//协议
			props.setProperty("mail.smtp.host", "smtp.126.com");//主机名
			props.setProperty("mail.smtp.port", "25");//端口号
			props.setProperty("mail.smtp.auth", "true");//是否开启权限控制
			props.setProperty("mail.debug", "true");//是否打印发送时的信息
			
			Session session = Session.getInstance(props);
			
			/**
			 * 2.创建邮件对象
			 */
			Message msg = new MimeMessage(session);
			//邮件发件人
			msg.setFrom(new InternetAddress("yi5620833@126.com","地表最强demo","utf-8"));
			//邮件标题
			msg.setSubject(title);
			//设置邮件内容
			msg.setContent(content, "text/html;charset=UTF-8");
			//设置邮件收件人
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,"尊敬的用户","utf-8"));
			
			/**
			 * 3.创建Transport对象，发送邮件
			 */
			Transport trans = session.getTransport();
			//连接服务器
			trans.connect("yi5620833","QEVNNDCEAFYHCJWC");
			//发送邮件
			trans.sendMessage(msg, msg.getAllRecipients());
			//关闭连接
			trans.close();
			result = true;
		} catch (Exception ex){
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
		return result;
	}
}
